//
//  MusicListViewController.m
//  NuwaRobot
//
//  Created by Kendama on 2017/12/6.
//  Copyright © 2017年 Kendama. All rights reserved.
//

#import "MusicListViewController.h"
#import "MusicHeadView.h"
#import "MusicTableViewCell.h"
#import "XMReqMgr.h"
#import "XMHotTrack.h"
#import "XMAlbum.h"
#import "DataManager.h"
#import "MJRefresh.h"

@interface MusicListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSMutableArray *dataSource;
@property(nonatomic,strong) MusicHeadView *tableHeaderView;
@property(nonatomic,assign) NSInteger index;
@property(nonatomic,assign)int page;

@end

@implementation MusicListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.index = -1;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateData:) name:XiMaLaYa object:nil];
    [[DataManager sharedInstance] sendCode:@"1012" data:@{}];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:XiMaLaYa];
}

#pragma mark --- 点击事件
- (void)didClickAllPlayButton
{
    if (self.tableHeaderView.playButton.selected)
    {
        [self playMusicWithIndex:-1 state:@"0"];
    }
    else
    {
        [self playMusicWithIndex:-1 state:@"1"];
    }
    self.tableHeaderView.playButton.selected = !self.tableHeaderView.playButton.selected;
    self.index = -1;
    [self.tableView reloadData];
}


#pragma mark --- 事件处理
- (void)playMusicWithIndex:(NSInteger)index state:(NSString *)state
{
    NSString *album_id = [NSString stringWithFormat:@"%li",(long)self.albumModel.albumId];
    NSString *indexString = [NSString stringWithFormat:@"%li",(long)index];
    [[DataManager sharedInstance] sendCode:@"1011" data:@{@"album_id":album_id,@"index":indexString,@"state":state}];
}

- (void)updateData:(NSNotification *)notification
{
    NSDictionary *dict = notification.userInfo;
    if (self.albumModel.albumId == [dict[@"album_id"] intValue])
    {
        if ([dict[@"state"] intValue] == 0) // 暂停
        {
            self.index = -1;
        }
        else
        {
            self.index = [dict[@"index"] intValue];
        }
        [self.tableView reloadData];
    }
    NSLog(@"喜马拉雅---%@",dict);
}

#pragma mark --- 数据更新
- (void)refreshBaseControlValue
{
    self.page = 1;
    [self updateTagInfoWithPage:self.page];
}

- (void)updateTagInfoWithPage:(int)page
{
    NSString *albumID = [NSString stringWithFormat:@"%li",(long)self.albumModel.albumId];
    NSDictionary *params = @{@"album_id":albumID,@"page":@(page).stringValue};
    [[XMReqMgr sharedInstance] requestXMData:XMReqType_AlbumsBrowse params:params withCompletionHander:^(id result, XMErrorModel *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if (!error)
        {
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:4];
            for (NSDictionary *dict in result[@"tracks"])
            {
                XMTrack *model = [[XMTrack alloc] initWithDictionary:dict];
                [array addObject:model];
            }
            if (array.count > 0)
            {
                if (self.page == 1)
                {
                    [self.dataSource removeAllObjects];
                    self.dataSource = array;
                }
                else
                {
                    [self.dataSource addObjectsFromArray:array];
                }
            }
            else
            {
                if (self.page > 1)
                {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }

            [self.tableView reloadData];
        }
        else
        {
            
        }
    }];
    
}

#pragma mark --- tabelview代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return px1920Height(220);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return px1920Height(30);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicTableViewCell *cell = [MusicTableViewCell cellWithTableView:tableView forIndexPath:indexPath];
    XMTrack *model = self.dataSource[indexPath.section];
    [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.coverUrlSmall] placeholderImage:imageWithName(@"pic")];
    cell.titleLabel.text = model.trackTitle;
    [cell setCountWithString:[NSString stringWithFormat:@"%li",(long)model.downloadCount]];
    [cell setDateWithString:[self formatTimeHourMiniuteSecond:model.duration]];
    if (indexPath.section == self.index)
    {
        cell.playButton.selected = YES;
    }
    else
    {
        cell.playButton.selected = NO;
    }
    __weak typeof(self) weakSelf = self;
    cell.playBlock = ^{
        if (weakSelf.index == indexPath.section) // 暂停
        {
            weakSelf.index = -1;
            [weakSelf playMusicWithIndex:indexPath.section state:@"0"];
        }
        else  // 播放
        {
            weakSelf.index = indexPath.section;
            [weakSelf playMusicWithIndex:indexPath.section state:@"1"];
        }
        [weakSelf.tableView reloadData];
    };

    return cell;
}

- (NSString *)getTenThousandCount:(NSInteger)count
{
    if (count > 10000)
    {
        return [NSString stringWithFormat:@"%.2f万",(float)count/10000];
    }
    else
    {
        return [NSString stringWithFormat:@"%li",(long)count];
    }
}

- (NSString *)getMinuteWithSecond:(NSInteger)second
{
    NSString *string = [NSString stringWithFormat:@"%li:%li",second/60,second%60];
    return string;
}

- (NSString *)formatTimeHourMiniuteSecond:(NSInteger)num{
    int sec = (int)num%60;
    int min = (int)num/60;
    int hour = (int)num/3600;
    
    if (hour == 0) {
        return [NSString stringWithFormat:@"%02d:%02d",min,sec];
    }
    
    return [NSString stringWithFormat:@"%02d:%02d:%02d",hour,min - 60 * hour,sec];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --- 懒加载
- (UITableView *)tableView
{
    if(!_tableView)
    {
        UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        [superView addSubview:_tableView];
        _tableView.backgroundColor = [UIColor clearColor];
//        _tableView.tableHeaderView = self.tableHeaderView;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.page = 1;
            [self updateTagInfoWithPage:self.page];
        }];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            self.page ++;
            [self updateTagInfoWithPage:self.page];
        }];
    }
    return _tableView;
}

- (NSMutableArray *)dataSource
{
    if(!_dataSource)
    {
        _dataSource = [[NSMutableArray alloc]init];
    }
    return _dataSource;
}


- (MusicHeadView *)tableHeaderView
{
    if (!_tableHeaderView)
    {
        UIView *superView = self.view;
        _tableHeaderView = [[MusicHeadView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, px1920Height(555))];
        [superView addSubview:_tableHeaderView];
        [_tableHeaderView.bgImageView sd_setImageWithURL:[NSURL URLWithString:self.albumModel.coverUrlLarge] placeholderImage:imageWithName(@"pic")];
        _tableHeaderView.nameLabel.text = self.albumModel.albumTitle;
        [_tableHeaderView.playButton addTarget:self action:@selector(didClickAllPlayButton) forControlEvents:UIControlEventTouchUpInside];

    }
    return _tableHeaderView;
}


- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    [self.tableHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(superView);
        make.height.mas_equalTo(px1920Height(555));
    }];
    
    UIButton *listButton = [[UIButton alloc] init];
    [superView addSubview:listButton];
    [listButton setTitle:@"音频列表" forState:UIControlStateNormal];
    [listButton setImage:imageWithName(@"icon_music") forState:UIControlStateNormal];
    [listButton setTitleColor:rgba(136,159,208,1) forState:UIControlStateNormal];
    [listButton layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:5];
    [listButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.tableHeaderView.mas_bottom).with.offset(px1920Height(47));
        make.left.mas_equalTo(superView.mas_left).with.offset(px1080Width(40));
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(listButton.mas_bottom).with.offset(px1920Height(20));
        make.left.mas_equalTo(superView.mas_left).with.offset(px1080Width(40));
        make.right.mas_equalTo(superView.mas_right).with.offset(-px1080Width(40));
        make.bottom.mas_equalTo(superView.mas_bottom);
    }];
    
    [self.view bringSubviewToFront:self.navigationBar];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
